package com.hefan.robot.listener;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.live.bean.RobotListenerVo;
import com.hefan.live.itf.LiveImOptService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.user.itf.WatchCacheService;
import com.hefan.user.itf.WatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by nigle on 2016/12/7.
 */
@Component
public class RobotActionWatchListener implements GLLMessageListener {

    Logger logger = LoggerFactory.getLogger(RobotActionWatchListener.class);

    @Resource
    WatchService watchService;
    @Resource
    LiveImOptService liveImOptService;
    @Resource
    LivingRedisOptService livingRedisOptService;

    @Resource
    private WatchCacheService watchCacheService;

    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFAN_ROBOT_ACTION_WATCH_DELAY ;
    }

    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return TopicRegistryDev.HEFAN_ROBOT_ACTION_WATCH_DELAY_DEV;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {
        return TopicRegistryTest.HEFAN_ROBOT_ACTION_WATCH_DELAY_TEST;
    }

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String realTopic = message.getTag();
        logger.info("直播中机器人关注-开始： receiver MessageListener topic: {}, realTopic : {}, msg_body: {}",
                message.getTopic(), realTopic, new String(message.getBody()));
        try {
            Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
            if (null != map && !map.isEmpty()) {
                String voStr = (String) map.get("vo");
                RobotListenerVo vo = JSONObject.parseObject(voStr, RobotListenerVo.class);
                if (null == vo) {
                    logger.info("RobotListenerVo解析失败");
                    return Action.CommitMessage;
                }
                if (!livingRedisOptService.isExistsLivingInfo_Hash(vo.getAnchId())) {
                    logger.info("直播{}已经结束，停止发送关注IM消息",vo.getLiveUuid());
                    return Action.CommitMessage;
                }
                if (!livingRedisOptService.IMSendCheck(vo.getAnchId(),3)){
                    logger.info("太多了不能再发送关注的IM消息了,{}",vo.getLiveUuid());
                    return Action.CommitMessage;
                }
                //判断是否还在直播间
                Long result = livingRedisOptService.isInRoom(vo.getAnchId(), vo.getLiveRoomPersonVo().getUserId());
                if (null == result) {
                    logger.info("{}已经不在{}的直播间了，停止动作",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId());
                    return Action.CommitMessage;
                }
                //是否关注过主播
                //int isWatch = watchService.isWatchedCheck(vo.getLiveRoomPersonVo().getUserId(), vo.getAnchId());
                int isWatch = watchCacheService.getWatchRelationByUserId(vo.getLiveRoomPersonVo().getUserId(), vo.getAnchId());
                logger.info("isWatch is{}" ,isWatch);
                if (isWatch == 0) {
                    //清除缓存中的关注信息
                    watchService.flushWatchRedis(vo.getAnchId());
                    //关注动作，参数0：不推送开播提醒
                    int row = watchService.fork(vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId(),0);
                    logger.info("关注业务返回结果：{}",row);
                    if ( row < 1){
                        logger.info("{}关注了主播{}",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId());
                        //发送关注IM文字消息，多发几次
                        ResultBean rb = liveImOptService.watchAnchor(vo.getChatRoomId(), vo.getLiveUuid(), vo.getLiveRoomPersonVo());
                        if ( null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                            logger.info("{}关注主播{}，发送IM消息成功，code：{}，msg：{}",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId(),String.valueOf(rb.getCode()),rb.getMsg());
                        }else {
                            rb = liveImOptService.watchAnchor(vo.getChatRoomId(), vo.getLiveUuid(), vo.getLiveRoomPersonVo());
                            if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                                logger.info("{}关注主播{}，发送IM消息成功，code：{}，msg：{}",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId(),String.valueOf(rb.getCode()),rb.getMsg());
                            }else {
                                rb = liveImOptService.watchAnchor(vo.getChatRoomId(), vo.getLiveUuid(), vo.getLiveRoomPersonVo());
                                if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                                    logger.info("{}关注主播{}，发送IM消息成功，code：{}，msg：{}",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId(),String.valueOf(rb.getCode()),rb.getMsg());
                                }else {
                                    logger.info("{}关注主播{}，发送IM消息尝试三次，失败，code：{}，msg：{}",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId(),String.valueOf(rb.getCode()),rb.getMsg());
                                }
                            }
                        }
                    }
                }else {
                    logger.info("{}已经关注过主播{}",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId());
                }
               return Action.CommitMessage;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("HEFAN_ROBOT_ACTION_WATCH_DELAY receiver MessageListener ERROR：" + e.getMessage());
            return Action.CommitMessage;
        } finally {
            logger.info("HEFAN_ROBOT_ACTION_WATCH_DELAY receiver MessageListener END");
            return Action.CommitMessage;
        }
    }
}
